﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;
using SafeCalculations.SafeTypes;

namespace SafeCalculations
{
    public static class CalculationExtensions
    {
        /// <summary>
        /// Calculates the average by creating the exact value as a fraction and then converting that to a double. No numeric overflow/underflow is posible as long as no more than int.MaxValue (2,147,483,647) values are used (no more than this could be used since then <paramref name="values"/>.Count wouldn't be able to accurately hold the correct number). 
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        public static double AverageNoOverflow(this int[] values)
        {
            if (values == null)
                throw new ArgumentNullException("values");

            Int32WithBoundedRollover sum = new Int32WithBoundedRollover();
            sum.Add(values);

            return SafeStatistics.CalculateAverage(sum, (uint)values.Length);
        }
    }
}
